import {
  defineComponent,
} from 'vue'

import {
  ElButton,
  ElCol,
  ElMessage,
  ElMessageBox,
  ElRow,
} from 'element-plus'
import { useRouter } from 'vue-router'
import DictTag from '@/components/DictTag/index.vue'

import usePageTable from '@/hooks/usePageTable'
import {
  deleteComprehensiveScore,
  getComprehensiveScoreList,
} from '@/api/scholarship'
import type { ComprehensiveScore } from '@/types/scholarship'
import { useDict } from '@/utils/dict'
import useUserStore from '@/store/modules/user'

export default defineComponent({
  setup() {
    const { sys_user_sex, sys_yes_no } = useDict('sys_user_sex', 'sys_yes_no')
    const router = useRouter()
    const currentUser = useUserStore()
    const handleAdd = () => {
      router.push('/scholarship/comprehensiveScoreDetail')
    }

    const handleEdit = (id: string | number) => {
      router.push({ path: '/scholarship/comprehensiveScoreDetail', query: { id } })
    }

    /** 列表逻辑 */
    const {
      Table,
      handleSearch,
    } = usePageTable<ComprehensiveScore>(
      {
        initValues: {
          studentCode: currentUser.name,
          pageSize: 10,
          pageNum: 1,
        },
        getList: getComprehensiveScoreList,
      },
      [
        {
          key: 'studentName',
          title: '学生姓名',
        },
        {
          key: 'sex',
          title: '性别',
          render: row =>
            <><DictTag value={row.sex} options={sys_user_sex.value} type="text" /></>,
        },
        {
          key: 'year',
          title: '年份',
        },
        {
          key: 'totalScore',
          title: '所得分数',
        },
        {
          key: 'isPass',
          title: '是否审核通过',
          render: row =>
            <><DictTag value={row.isPass} options={sys_yes_no.value} type="tag" /></>,
        },
        {
          key: 'operate',
          title: '操作',
          render: row => (
            <>
              <ElButton link type="primary" icon="Edit" onClick={() => handleEdit(row.id)}>修改</ElButton>
              <ElButton link type="danger" icon="Delete" onClick={() => handleDelete(row.id)}>删除</ElButton>
            </>
          ),
        },
      ],
    )
    void handleSearch()

    function handleDelete(id: string | number) {
      ElMessageBox.confirm(`确认要"删除"这条记录吗?`).then(async () => {
        await deleteComprehensiveScore(id)
        ElMessage.success('操作成功')
        void handleSearch()
      })
    }

    return () => (
      <div class="p-2 md:p-4 h-full">
        <ElRow gutter={10} class="mb-4">
          <ElCol span={1.5}>
            <ElButton
              type="primary"
              plain
              icon="Plus"
              onClick={handleAdd}
            >
              新增
            </ElButton>
          </ElCol>
        </ElRow>
        <Table />
      </div>
    )
  },
})
